import { useState, useMemo, useEffect } from "react";
import Header from "@/components/header";

import { Toast, Input } from "antd-mobile";
import { BackgroundButton } from "@/components/button";
import "./index.less";
import priBtn from "@/assets/images/priBtn.png";
import defBtn from "@/assets/images/defBtn.png";
import aijiadouIco from "@/assets/images/aijiadou.png";
import { useNavigate } from "react-router-dom";
import CustomModal from "../../components/customModal";
import { useLocalStorageState } from "ahooks";

function DeductBeans() {
  const [exchange, setExchange] = useState(); // 本次兑换（豆）
  const [visible, setVisible] = useState(false);
  const navigate = useNavigate();
  const params = new URLSearchParams(location.search);
  const point = params.get("point");
  const [beans, setBeans] = useState(point || 0); // 当前智豆
  const [_, setDeductCount] = useLocalStorageState("DEDUCT_COUNT");

  const remain = useMemo(() => {
    const num = Number(exchange || 0);
    if (!Number.isFinite(num)) return beans;
    return Math.max(beans - num, 0);
  }, [beans, exchange]);

  const handleChange = (val) => {
    const onlyNum = (val || "").replace(/[^0-9]/g, "");
    setExchange(onlyNum);
  };

  const handleBlur = () => {
    if (!exchange) return;
    const num = parseInt(exchange, 10) || 0;
    if (num % 10 !== 0) {
      Toast.show({ content: "请输入10的整数倍", maskClickable: false });
      const snapped = Math.floor(num / 10) * 10;
      setExchange(snapped ? String(snapped) : "");
    }
  };

  const handleConfirm = () => {
    const num = Number(exchange);
    if (!num) {
      Toast.show({ content: "请输入兑换数量",maskClickable: false  });
      return;
    }
    if (num % 10 !== 0) {
      Toast.show({ content: "兑换需为10的倍数",maskClickable: false  });
      return;
    }
    if (num > beans) {
      Toast.show({ content: "兑换数量超过可用智豆" ,maskClickable: false });
      return;
    }
    try {
      onOkExchange();
    } catch (error) {
      Toast.show({ content: "抵扣失败，请重试" });
    }
  };

  const onOkExchange = () => {
    Toast.show({ content: "抵扣成功",maskClickable: false  });
    setVisible(false);
    setDeductCount(exchange);
    setTimeout(() => {
      navigate(`/paycode`, { replace: true });
    }, 100);
  };

  const handleBack = () => {
    history.back();
  };

  return (
    <div className="deduct-page">
      <Header />
      <div className="deduct-content">
        <div className="beans-card">
          <div className="card-top">
            <div className="beans-info">
              <div className="beans-title">当前数智豆余额(豆)</div>
              <div className="beans-amount">{beans}</div>
              <div className="beans-subtext">100数智豆可抵扣1元</div>
            </div>
            <img src={aijiadouIco} alt="数智豆" className="beans-icon" />
          </div>
          <div className="beans-line"></div>

          <div className="exchange-section">
            <div className="exchange-left">
              <div className="label">本次兑换(豆)</div>
              <div className="input-wrap">
                <Input
                  value={exchange}
                  onChange={handleChange}
                  onBlur={handleBlur}
                  placeholder="请输入兑换数量"
                  clearable
                />
              </div>
            </div>
            <div className="exchange-right">
              <div className="label">兑换后剩余（豆）</div>
              <div className="remain">{remain ? remain : "/"}</div>
            </div>
          </div>
        </div>
      </div>

      <CustomModal
        visible={visible}
        position={"center"}
        mode={"confirm"}
        title="是否确认抵扣"
        message="请仔细核对是否要抵扣该数量？"
      />

      <div className="deduct-footer">
        <BackgroundButton
          type="primary"
          backgroundImage={priBtn}
          block
          onClick={() => handleConfirm()}
        >
          确认抵扣
        </BackgroundButton>
        <BackgroundButton
          type="default"
          backgroundImage={defBtn}
          block
          onClick={handleBack}
        >
          返回
        </BackgroundButton>
      </div>
    </div>
  );
}

export default DeductBeans;
